﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CrumbPlus.Core.Crumb;
using SharpDiary.Core.Data;
using SharpDiary.Core.Utility;

namespace CrumbPlus.UI
{
    public partial class FrmCrumbInfoEditor : Form
    {
        private CrumbInfo _crumb;

        public CrumbInfo Crumb
        {
            get { return _crumb; }
            set
            {
                _crumb = value;

                btnOk.Text = (value != null ? "更新" : "创建");
                txtTaskName.Text = (value != null ? _crumb.Name : string.Empty);
            }
        }

        public FrmCrumbInfoEditor()
        {
            InitializeComponent();
        }

        private bool CheckInputOk()
        {
            if (txtTaskName.Text.Trim().Length == 0)
            {
                MessageBoxHelper.ShowMessage("请输入任务名称。");
                txtTaskName.Focus();
                txtTaskName.SelectAll();

                return false;
            }

            return true;
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            if (!CheckInputOk()) { return; }

            if (_crumb == null)
            {
                _crumb = new CrumbInfo();
                _crumb.Name = txtTaskName.Text;
                _crumb.CreateTime = DateTime.Now;
                _crumb.Code = Guid.NewGuid().ToString();

                bool result = DbObjectMappingHelper.Create<CrumbInfo>(_crumb);
                if (!result)
                {
                    this.DialogResult = DialogResult.Cancel;
                    MessageBoxHelper.ShowAlert("保存失败，请稍候再试。");
                }
                else
                {
                    this.DialogResult = DialogResult.OK;
                    Close();
                }
            }
            else
            {
                _crumb.Name = txtTaskName.Text;
                _crumb.CreateTime = DateTime.Now;

                bool result = DbObjectMappingHelper.Update<CrumbInfo>(_crumb);
                if (!result)
                {
                    this.DialogResult = DialogResult.Cancel;
                    MessageBoxHelper.ShowAlert("保存失败，请稍候再试。");
                }
                else
                {
                    this.DialogResult = DialogResult.OK;
                    Close();
                }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            Close();
        }
    }
}
